package com.kx.game.center.serverDistribution;

import com.alibaba.fastjson.JSONObject;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.redis.RedisConstant;
import com.redis.core.manager.RedisManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

public class NearbyDistribution implements ServerDistributionInterface{

    @Override
    public JSONObject execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        RedisManager redisManager = GSServices.redisServer.getRedisClient();
        Set<Object> serverCreateNum = redisManager.hashKeys(RedisConstant.SERVER_CREATE_NUM);
        for (Object _serverCreateNum : serverCreateNum){
            String serverKey = String.valueOf(_serverCreateNum);
            if (Integer.parseInt(serverKey) == GSServices.serverConfig.getFriendServerId())
                continue;
            int num = Integer.parseInt(redisManager.hashGet(RedisConstant.SERVER_CREATE_NUM, serverKey, String.class));
            if (GSServices.serverConfig.getServerPlayerNum() > num){
                JSONObject jsonObject = GSServices.localManager.getGameServerInfo(serverKey);
                return GSServices.localManager.getJson(
                        ResponseState.SUCCESS,String.valueOf(jsonObject.get("ip")),String.valueOf(jsonObject.get("gamePort")));
            }
        }
        return GSServices.localManager.getJson(ResponseState.SERVER_NUM_FULL,null, null);
    }
}
